/**
 * 
 */
package by.imotaeva.printing_services.dataaccess.impl;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import by.imotaeva.printing_services.dataaccess.BindingOrderDao;
import by.imotaeva.printing_services.datamodel.BindingOrder;
import by.imotaeva.printing_services.datamodel.BindingOrder_;
import by.imotaeva.printing_services.datamodel.PrintingProductOrder_;

/**
 * @author Inna
 *
 */
@Repository
public class BindingOrderDaoImpl extends AbstractDaoImpl<Long, BindingOrder> implements BindingOrderDao {

	protected BindingOrderDaoImpl() {
		super(BindingOrder.class);
	}

	@Override
	public List<Long> getBindingOrderIds() {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<Long> criteria = cBuilder.createQuery(Long.class);
		Root<BindingOrder> root = criteria.from(BindingOrder.class);

		criteria.select(root.get(BindingOrder_.id));

		TypedQuery<Long> query = getEm().createQuery(criteria);
		List<Long> results = query.getResultList();
		return results;
	}

	@Override
	public Long getCount() {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<Long> criteria = cBuilder.createQuery(Long.class);
		Root<BindingOrder> root = criteria.from(BindingOrder.class);

		criteria.select(cBuilder.count(root));

		TypedQuery<Long> query = getEm().createQuery(criteria);
		return query.getSingleResult();
	}

	@Override
	public BindingOrder getFullBindingOrder(Long id) {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<BindingOrder> criteria = cBuilder.createQuery(BindingOrder.class);
		Root<BindingOrder> root = criteria.from(BindingOrder.class);

		criteria.select(root);
		root.fetch(BindingOrder_.paper, JoinType.LEFT);
		root.fetch(BindingOrder_.carboard);
		root.fetch(BindingOrder_.bindingMaterial);
		root.fetch(BindingOrder_.printingProductOrder).fetch(PrintingProductOrder_.customer);

		criteria.where(cBuilder.equal(root.get(BindingOrder_.id), id));

		TypedQuery<BindingOrder> query = getEm().createQuery(criteria);
		BindingOrder result = query.getSingleResult();
		return result;
	}

}
